const express = require('express');
const router = express.Router();
const multer = require('multer');
const fs = require('fs');
const mysql = require("../util/mysql/mysql");
 
let upload = multer({
    storage: multer.diskStorage({
        destination: function (req, file, cb) {
            cb(null, './uploads/');
        },
        filename: function (req, file, cb) {
            var changedName = (new Date().getTime())+'-'+file.originalname;
            cb(null, changedName);
        }
    })
});
 
//单个文件上传
router.post('/single',upload.single('file'),(req, res) => {
    res.send(JSON.stringify({code: '1',filename:req.file.filename}))
});
// 上传申报书
router.post("/fileName", function (req, res, next) {
    const [fileName,p_id,p_apply_id] = [req.body.fileName,req.body.p_id,req.body.u_id];
    mysql.data(
      "UPDATE project_mainmas SET p_application=? WHERE p_id=?",
      [fileName,p_id],
      function (err, rows, fields) {
        if (err) {
            return
        }else{
            mysql.data(
                "UPDATE project SET p_type=11,p_apply_id=? WHERE id=?",
                [p_apply_id,p_id],
                function (err, rows, fields) {
                  if (err) return;
                  res.send(
                    JSON.stringify({code: 1,})
                  );
                }
              );
        };
        
      }
    );
  });
// 上传结业报告
router.post("/upFinish", function (req, res, next) {
    const [fileName,p_id] = [req.body.fileName,req.body.p_id];
    console.log(fileName,p_id);
    mysql.data(
      "UPDATE project_mainmas SET p_finish=? WHERE p_id=?",
      [fileName,p_id],
      function (err, rows, fields) {
        if (err) {
            return
        }else{
            mysql.data(
                "UPDATE project SET p_type=2 WHERE id=?",
                [p_id],
                function (err, rows, fields) {
                  if (err) return;
                  res.send(
                    JSON.stringify({code: 1,})
                  );
                }
              );
        };
        
      }
    );
  });
//下载申报表
router.get('/download',function (req,res) {
    mysql.data(
        "SELECT p_application FROM project_mainmas WHERE p_id=?",
        [req.query.p_id],
        function (err, rows, fields) {
          if (err) return;
          res.download('uploads/'+rows[0].p_application);
        }
      )
    
})
//下载结业报告
router.get('/downOverReport',function (req,res) {
    mysql.data(
        "SELECT p_finish FROM project_mainmas WHERE p_id=?",
        [req.query.p_id],
        function (err, rows, fields) {
          if (err) return;
          res.download('uploads/'+rows[0].p_finish);
        }
      )
    
})

  
module.exports = router;